// i.d(t, { z: () => InstancedPinHeads })
import Logger from "../utils/Logger"
import * as THREE from "three"
import { InstancedPinHeadMaterial, PinHeadCustomMaterial } from "../material/PinMaterial"
import renderOrderEnum from "../enum/renderOrder.enum"
import configConst from "../constant/config.const"
import { pinItemData } from "../module/PinsModule"
const l = new Logger("InstancedPinHeads")
export default class InstancedPinHeads extends THREE.InstancedMesh {
  maxCount: number
  opacityArray: Float32Array
  opacityAttrib: THREE.InstancedBufferAttribute
  renderedPins: pinItemData[]
  constructor(e: number, t: THREE.Texture, i: THREE.Texture, s?: boolean) {
    const l = new THREE.PlaneBufferGeometry(configConst.BasePlaneSize, configConst.BasePlaneSize)
    const c = new Float32Array(e)
    const h = new THREE.InstancedBufferAttribute(c, 1)
    l.setAttribute("instanceAlpha", h)
    super(l, s && i ? new InstancedPinHeadMaterial(t, i) : new PinHeadCustomMaterial(t, !0), e)
    this.maxCount = e
    this.opacityArray = c
    this.opacityAttrib = h
    this.setColorAt(0, new THREE.Color())
    this.renderedPins = []
    this.renderOrder = renderOrderEnum.pins
  }
  update(e: pinItemData[]) {
    let t = 0
    this.renderedPins.length = 0
    for (const i of e) {
      if (i.visible) {
        if (t >= this.maxCount) {
          l.error("Instance count is too small!")
        } else {
          this.setMatrixAt(t, i.pinHeadMatrix)
          this.setColorAt(t, i.pinColor)
          this.opacityArray[t] = i.opacity * i.opacityAnimation.value
          t++
          this.renderedPins.push(i)
        }
      }
    }

    this.count = t
    this.visible = this.count > 0
    this.instanceMatrix.needsUpdate = !0
    this.opacityAttrib.needsUpdate = !0
    this.instanceColor ? (this.instanceColor.needsUpdate = !0) : l.error("Instance color should be defined")
  }
}
